<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="7" :xs="24">
        <!-- 左侧树 -->
        <div class="col-tree">
          <div class="title">{{ $t("巡检对象树") }}</div>
          <div class="tree-input">
            <el-input
              v-model="objTreeInput"
              :placeholder="$t('节点对象名称巡检点名称识别类型')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="tree-body">
            <el-tree
              :data="deptOptions"
              node-key="treeId"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :default-checked-keys="[]"
              :current-node-key="currentTreeId"
              class="scroll-hidden"
              ref="objTree"
              default-expand-all
              @node-click="nodeClick($event)"
            >
              <span
                style="display: inline-block; width: 100%"
                :style="
                  data.treeId == currentTreeId
                    ? 'background-color:rgba(0, 209, 255, 0.2)'
                    : ''
                "
                slot-scope="{ node, data }"
              >
                <img
                  :src="icons[data.iconType]"
                  style="width: 16px; height: 16px"
                />
                <span
                  style="
                    margin-left: 10px;
                    display: inline-block;
                    width: 197px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                  :style="{
                    color:
                      data.type == '2' && data.isParam == '0'
                        ? '#FF5562'
                        : '#FFFFFF',
                  }"
                  :title="data.name"
                  >{{ data.name }}</span
                >
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="17" :xs="24">
        <!-- 右侧 -->
        <div class="right-col">
          <!-- 搜索区域 -->
          <div class="search-area">
            <div class="form">
              <el-form
                :model="listQuery"
                ref="queryForm"
                size="mini"
                :inline="true"
                label-width="130px"
              >
                <el-form-item :label="$t('开始时间') + ':'">
                  <el-date-picker
                    v-model="listQuery.startTime"
                    type="datetime"
                    size="medium"
                    :placeholder="$t('选择开始时间')"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    default-time="['00:00:00', '23:59:59']"
                    :picker-options="pickerOptionsStart"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('结束时间') + ':'">
                  <el-date-picker
                    v-model="listQuery.endTime"
                    type="datetime"
                    size="medium"
                    :placeholder="$t('选择结束时间')"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    default-time="['00:00:00', '23:59:59']"
                    :picker-options="pickerOptionsEnd"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('任务名称') + ':'" prop="taskName">
                  <el-input
                    v-model="listQuery.taskName"
                    :placeholder="$t('请输入')"
                    clearable
                    size="medium"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
              </el-form>
            </div>
            <div class="btns search-area-btn">
              <div
                v-hasPermi="['data:objectData:search']"
                @click="searchBtn"
                class="serch-btn cursor-pointer"
                style="width: 80px"
              >
                {{ $t("搜索") }}
              </div>
              <div
                v-hasPermi="['data:objectData:reset']"
                @click="resetBtn"
                class="reset-btn cursor-pointer"
                style="width: 80px"
              >
                {{ $t("重置") }}
              </div>
            </div>
          </div>
          <!-- 图表 -->
          <div class="charts">
            <span
              class="tooltoop"
              v-if="enumMapList.length !== 0"
              style="
                width: 70%;
                display: flex;
                flex-direction: row;
                justify-content: flex-end;
              "
            >
              <span
                v-for="(item, index) in enumMapList"
                :key="index"
                style="margin-left: 24px"
              >
                <span>
                  <span style="color: #00d1ff"
                    >&nbsp;&nbsp;&nbsp;{{ item.enumNumber }}:</span
                  >
                  <span style="color: #fff">{{ item.enumValue }}</span>
                </span>
              </span>
            </span>
            <div id="chart" style="height: 297px; width: 100%"></div>
            <!-- <lineChart
              ref="lineChart"
              :lineChartAll="lineChartData"
              :xAxis="xAxis"
              :name="name"
              :percentOfTen="percentOfTen"
              @chartClick="chartClick"
            ></lineChart> -->
          </div>
          <!-- 表格 -->
          <div class="table">
            <div class="self">
              <el-table
                ref="tableRef"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
              >
                <el-table-column type="selection"> </el-table-column>
                <el-table-column
                  width="80"
                  prop="taskExecId"
                  :label="$t('任务ID')"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  width="100"
                  :label="$t('任务名称')"
                  prop="taskName"
                  align="center"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  width="150"
                  prop="deviceName"
                  :label="$t('巡检对象名称')"
                  align="center"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  :label="$t('识别时间')"
                  show-overflow-tooltip
                  align="center"
                  width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="recognitionName"
                  :label="$t('识别类型')"
                  show-overflow-tooltip
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="deviceResult"
                  :label="$t('识别结果')"
                  show-overflow-tooltip
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="resource"
                  :label="$t('采集信息')"
                  show-overflow-tooltip
                  align="center"
                >
                  <template slot-scope="scope">
                    <span
                      v-for="(item, index) in scope.row.resourceType"
                      :key="index"
                      class="column-imgs"
                    >
                      <img
                        src="../../../assets/images/objectData/picture.png"
                        alt=""
                        @click="rowClick(scope.row, index, 'showPic')"
                        v-if="item == '0'"
                      />
                      <img
                        src="../../../assets/images/objectData/video.png"
                        alt=""
                        @click="rowClick(scope.row, index, 'showVideo')"
                        v-if="item == '1'"
                      />
                      <img
                        src="../../../assets/images/objectData/audio.png"
                        alt=""
                        @click="rowClick(scope.row, index, 'showAudio')"
                        v-if="item == '2'"
                      />
                    </span>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  prop="checkStatus"
                  :label="$t('审核结果')"
                  show-overflow-tooltip
                  align="center"
                >
                  <template slot-scope="scope">
                    <div
                      :style="{
                        color: scope.row.checkStatus == 0 ? '' : 'gray',
                      }"
                    >
                      {{
                        scope.row.checkStatus == 0 ? $t("未审核") : $t("已审核")
                      }}
                    </div>
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
            <div class="pagenation">
              <pagination
                :total="total"
                :page.sync="listQuerySubmit.pageNum"
                :limit.sync="listQuerySubmit.pageSize"
                @pagination="getTableList"
              >
              </pagination>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- dialog -->
    <el-dialog
      :title="$t('查看')"
      :visible.sync="dialogVisible"
      width="560px"
      @close="closeDialog"
    >
      <!-- 图片 -->
      <div
        v-if="
          dialogBooArr.find((item) => {
            return item.title == 'showPic';
          }).bool
        "
      >
        <div class="dialog-lineone">
          <div>{{ $t("拍摄时间") + "：" }}{{ dialogDetail.createTime }}</div>
          <div>{{ $t("文件名") + "：" }}{{ dialogDetail.resourceName }}</div>
          <div @click="downLoad" class="el-icon-download cursor-pointer"></div>
        </div>
        <div>
          <img style="width: 100%" :src="dialogSrc" alt="" />
        </div>
      </div>
      <!-- 视频 -->
      <div
        v-if="
          dialogBooArr.find((item) => {
            return item.title == 'showVideo';
          }).bool
        "
      >
        <div class="dialog-lineone">
          <div>{{ $t("录制时间") }}{{ dialogDetail.createTime }}</div>
          <div>{{ $t("文件名") }}{{ dialogDetail.resourceName }}</div>
          <div @click="downLoad" class="el-icon-download cursor-pointer"></div>
        </div>
        <div>
          <video controls style="width: 100%" ref="showVideo">
            <source :src="dialogSrc" type="video/mp4" />
          </video>
        </div>
      </div>
      <!-- 音频 -->
      <div
        v-if="
          dialogBooArr.find((item) => {
            return item.title == 'showAudio';
          }).bool
        "
      >
        <div class="dialog-lineone">
          <div>{{ $t("录制时间") }}{{ dialogDetail.createTime }}</div>
          <div>{{ $t("文件名") }}{{ dialogDetail.resourceName }}</div>
          <div @click="downLoad" class="el-icon-download cursor-pointer"></div>
        </div>
        <div class="display:flex" v-if="currentAudioUrl.src != ''">
          <aplayer :music="currentAudioUrl" ref="showAudio"></aplayer>
          <div class="change-audio">
            <div class="reset-btn el-icon-arrow-left"></div>
            <div class="reset-btn el-icon-arrow-right"></div>
          </div>
        </div>
      </div>
      <div slot="footer" style="display: flex; justify-content: flex-end">
        <div class="reset-btn" @click="dialogVisible = false">
          {{ $t("取消") }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import aplayer from "vue-aplayer";
import { API_treeOption, API_resultCompared } from "@/api/data/objData";
import {
  API_devictpageInfoList,
  API_getResourceinfo,
} from "@/api/data/inspectrecords.js";
import lineChart from "./components/lineChart.vue";
import moment from "moment";
import CircleStyle from "ol/style/Circle";
import * as echarts from "echarts";
import { chartOption } from "./components/option.js";
/**
 * 历史数据
 */
export default {
  dicts: ["recognition", "structType"],
  components: {
    aplayer,
    lineChart,
  },
  data() {
    return {
      sevePort: window.location.protocol + "//" + window.location.host,
      // 折线图数据
      lineChartData: [],
      xAxis: [], //x轴
      name: "", //y轴单位
      percentOfTen: "", //近十条数据拖拽值
      pickerOptionsStart: {
        disabledDate: (time) => {
          let endDateVal = this.listQuery.endTime;
          if (endDateVal) {
            return (
              time.getTime() >=
              new Date(endDateVal).getTime() + 1 * 24 * 60 * 60 * 1000
            );
          }
        },
      },
      // 结束日期
      pickerOptionsEnd: {
        disabledDate: (time) => {
          let beginDateVal = this.listQuery.startTime;
          if (beginDateVal) {
            return (
              time.getTime() <
              new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
            );
          }
        },
      },
      objTreeInput: undefined, //搜索框数据
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询条件
      listQuery: {
        taskName: "",
        startTime: moment().subtract(1, "months").format("YYYY-MM-DD HH:mm:ss"),
        endTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      listQuerySubmit: {},
      tableData: [], //表格数据
      selectedTableData: [], //表格选中数据
      //tree图标
      icons: {
        1: require("@/assets/images/objectData/rootobj.png"), //根节点
        2: require("@/assets/images/objectData/jiedianobj.png"), //节点
        3: require("@/assets/images/objectData/ptstobj.png"), //普通实体对象
        4: require("@/assets/images/objectData/ptxnobj.png"), //普通虚拟对象
        5: require("@/assets/images/objectData/hsstobj.png"), //红色实体对象
        6: require("@/assets/images/objectData/hsxnobj.png"), //红色虚拟对象
      },
      currentTreeId: "", // 被选中的树id 且type==2
      dialogSrc: "", //弹框URL
      dialogDetail: {}, //弹框图片数据
      currentAudioUrl: {
        src: "",
      }, //音频
      dialogVisible: false, //图片dialog
      //控制弹框展示组件
      dialogBooArr: [
        {
          title: "showPic",
          bool: false,
        },
        {
          title: "showVideo",
          bool: false,
        },
        {
          title: "showAudio",
          bool: false,
        },
      ],
      enumMapList: [
        {
          enumNumber: "",
          enumValue: "",
        },
      ], // 枚举模式折线图图例
      downLoadUrl: "",
      chart: null,
    };
  },
  watch: {
    objTreeInput(val) {
      this.getTreeData(val);
      // this.$refs.objTree.filter(val);
    },
  },
  created() {
    this.listQuerySubmit = Object.assign({}, this.listQuery);
    this.listQuerySubmit.startTime = "";
    this.listQuerySubmit.endTime = "";
    // this.getTableList(); //表格数据
    this.getTreeData(""); //树节点数据
  },
  mounted() {},
  methods: {
    /**折线图点击事件 */
    chartClick(params) {
      console.warn("数据数据数据", params);
    },
    /**获取折线图数据 */
    objAnalysis() {
      let obj = {
        startTime: this.listQuerySubmit.startTime,
        endTime: this.listQuerySubmit.endTime,
        taskName: this.listQuerySubmit.taskName,
        nodeList: this.currentTreeId,
      };
      API_resultCompared(obj).then((res) => {
        if (res.code == 200) {
          if (res.list.length !== 0) {
            let xdata = [];
            let ydata = [];
            if (res.list[0].dataType == 0) {
              this.enumMapList = [];
            } else if (res.list[0].dataType == 1) {
              let enumMapList = JSON.parse(res.list[0].enumMapValue);
              this.enumMapList = enumMapList;
            }
            res.list[0].lineList.forEach((item) => {
              xdata.push(moment(item.xdata).format("HH:mm"));
              ydata.push(item.ydata);
            });
            this.lineChartData = [
              {
                name: res.list[0].recognition,
                type: "line",
                data: ydata,
              },
            ];
            this.xAxis = xdata;
            if (Number(res.list[0].percentOfTen) >= 100) {
              this.percentOfTen = "0";
            } else {
              this.percentOfTen = String(
                100 - Number(res.list[0].percentOfTen)
              );
            }
            this.name = res.list[0].unit;
            this.initChart(
              this.lineChartData,
              xdata,
              this.name,
              this.percentOfTen
            );
            //数据传输 触发父组件内部方法
            // this.$refs.lineChart.initChart(
            //   this.lineChartData,
            //   xdata,
            //   this.name,
            //   this.percentOfTen
            // );
          } else {
            this.enumMapList = [];
            this.initChart([], []);
          }
        }
      });
    },
    initChart(data, xAxis, name, percentOfTen) {
      let chartDom = document.getElementById("chart");
      this.chart = echarts.init(chartDom);
      const option = chartOption(data, xAxis, name, percentOfTen);
      this.chart.setOption(option, true);
      // let this_ = this;
      // this.chart.on("click", function (params) {
      //   // 控制台打印数据的名称
      //   this_.$emit("chartClick", params);
      //   // console.warn("数据数据", params);
      // });
    },
    /**搜索 */
    searchBtn() {
      if (
        new Date(this.listQuery.endTime < this.listQuery.startTime).getTime()
      ) {
        this.$message.warning(this.$t("开始时间不能大于结束时间！"));
        return false;
      }
      this.listQuery.pageNum = 1;
      this.listQuerySubmit = Object.assign({}, this.listQuery);
      this.objAnalysis(); //折线图数据
      this.getTableList(); //表格数据
    },
    /**树 点击 */
    nodeClick(node) {
      this.listQuery.pageNum = 1;
      this.listQuerySubmit = Object.assign({}, this.listQuery);
      this.currentTreeId = node.treeId;
      this.getTableList();
      this.objAnalysis();
    },
    /**表格点击视频音频事件 */
    rowClick(rowInfo, index, type) {
      let id = rowInfo.resourceId[index];
      //展示图片、视频、音频
      this.dialogSrc = "";
      API_getResourceinfo({ id: id }).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            switch (type) {
              case "showPic":
                this.dialogSrc = this.sevePort + res.data.resourceUrl;
                break;
              case "showVideo":
                this.$refs.showVideo.src = this.sevePort + res.data.resourceUrl;
                break;
              case "showAudio":
                this.currentAudioUrl = {
                  src: this.sevePort + res.data.resourceUrl,
                  title: res.data.resourceName,
                };
                break;
            }
            this.dialogDetail = res.data;
            this.downLoadUrl = res.data.resourceUrl;
            this.dialogVisible = true;
          } else {
            this.$message.error(this.$t("暂无数据"));
          }
        } else {
          this.dialogSrc = "";
          this.dialogDetail = {};
        }
      });
      this.dialogBooArr.forEach((item) => {
        if (item.title == type) {
          item.bool = true;
        } else {
          item.bool = false;
        }
      });
    },
    downLoad() {
      this.$download.resource(this.downLoadUrl);
    },
    /**table数据 */
    getTableList() {
      //处理审核状态
      let checkStatusList = this.listQuerySubmit.checkStatusList;
      if (checkStatusList && checkStatusList.length > 0) {
        if (checkStatusList.indexOf(",") == -1) {
          checkStatusList = String(checkStatusList);
        } else {
          checkStatusList = checkStatusList.join(",");
        }
      }
      let obj = {
        ...this.listQuerySubmit,
        startTime: this.listQuerySubmit.startTime,
        endTime: this.listQuerySubmit.endTime,
        checkStatusList: checkStatusList,
        nodeList: this.currentTreeId,
        unit: this.lineType,
      };
      API_devictpageInfoList(obj).then((res) => {
        if (res.code == 200) {
          if (res.rows.length > 0) {
            this.tableData = res.rows;
            this.tableData.forEach((item) => {
              let resourceType = item.resourceType || "";
              let resourceId = item.resourceId || "";
              item.resourceType = resourceType.split(",");
              item.resourceId = resourceId.split(",");
            });
          } else {
            this.tableData = [];
          }
          this.total = Number(res.total);
          this.listQuery = Object.assign({}, this.listQuerySubmit);
        }
      });
    },
    /** 查询部门下拉树结构 */
    getTreeData(data) {
      API_treeOption({ name: data }).then((res) => {
        if (res.code == "200") {
          this.deptOptions = res.deviceTrees;
          this.treeGlxs(this.deptOptions);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 递归查询第一个
    treeGlxs(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length !== 0) {
          this.treeGlxs(data[i].children);
        } else {
          this.$nextTick().then(() => {
            this.$refs["objTree"].setCurrentKey(data[i].treeId);
            this.nodeClick(data[i]);
          });
          break;
        }
        break;
      }
    },
    /**树 筛选节点 */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /**table 多选数据 */
    selectionChange(val) {
      this.selectedTableData = val;
    },
    /**close dialog */
    closeDialog() {
      this.dialogVisible = false;
      this.dialogBooArr.forEach((item) => {
        if (item.title == "showPic") return;
        if (item.bool) {
          this.$refs[item.title].pause();
        }
      });
    },
    /**重置 */
    resetBtn() {
      this.listQuery = {
        taskName: "",
        startTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10,
      };
      this.$refs.objTree.setCheckedKeys([]);
      // this.currentTreeId = "";
      this.searchBtn();
    },
  },
};
</script>
<style lang="scss" scoped>
// 树
.col-tree {
  height: 920px;
  padding: 24px;
  box-sizing: border-box;
  border-right: 2px solid #314353;
  .title {
    font-size: 18px;
    font-weight: 500;
    color: #00d1ff;
  }
  .tree-input {
    margin-top: 15px;
  }
}
.right-col {
  height: 920px;
}
//搜索
.search-area {
  display: flex;
  width: 100%;
  box-sizing: border-box;
  // background-color: rgba(255, 255, 255, 0.08);
  .form {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    padding: 22px 16px 0 16px;
  }
  .btns {
    display: flex;
    width: 200px;
    padding: 8px;
    justify-content: space-around;
    align-items: center;
    border-left: 1px dashed rgba(219, 255, 251, 0.2);
  }
}
//表格
.table {
  height: 474px;
  padding: 24px;
  box-sizing: border-box;
  position: relative;
  .pagenation {
    position: absolute;
    bottom: 30px;
    right: 20px;
  }
}
.column-imgs {
  img {
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
.column-btn {
  display: flex;
  width: 44px;
  height: 32px;
  justify-content: center;
  align-items: center;
  font-size: 14px;
}
// 折线图
.charts {
  position: relative;
  height: 361px;
  display: flex;
  align-items: center;
  .tooltoop {
    position: absolute;
    top: 5%;
    right: 5%;
    width: 95px;
    min-height: 30px !important;
    line-height: 20px !important;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8px 0;
    font-size: 14px;
    span {
      display: inline-block !important;
      color: none !important;
    }
  }
}
/** 音频播放器*/
.aplayer {
  background-color: transparent;
  color: #fff;
  .aplayer-body {
    display: flex;
    flex-direction: column;
    .aplayer-pic {
    }
  }
}
/**弹框样式 */
.dialog-lineone {
  display: flex;
  margin: 0 0 20px 0;
  div:nth-child(1) {
    width: 50%;
  }
  div:nth-child(2) {
    width: 45%;
  }
  div:nth-child(3) {
    width: 5%;
  }
}
.change-audio {
  display: flex;
  margin-top: 20px;
  justify-content: center;
  div:nth-child(2) {
    margin-left: 20px;
  }
}
.scroll-hidden {
  height: 620px;
  overflow: auto;
}
.scroll-hidden::-webkit-scrollbar {
  display: none;
}

::v-deep {
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 195px;
  }

  .el-form-item__content {
    width: 150px;
  }
}
::v-deep {
  .el-dialog:not(.is-fullscreen) {
    margin-top: 30vh !important;
  }
  .self {
    .el-table__body-wrapper {
      width: 100%;
      max-height: 310px;
      overflow: auto;
    }
  }
}
</style>
